package cn.wolfcode.rocketmq._02_send_way;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

public class Producer {
    public static void main(String[] args) throws Exception {
        //1 创建一个生产者对象, 并且指定一个生产者组
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("product-demo");
        //发送消息超时时间
        defaultMQProducer.setSendMsgTimeout(10000);
        //2 绑定nameser名字服务的地址
        defaultMQProducer.setNamesrvAddr("localhost:9876");

        final CountDownLatch countDownLatch=new CountDownLatch(100);

        //3 启动生产者
        defaultMQProducer.start();

        for (int i = 0; i <100; i++) {
            //4 创建一个消息对象，把要发的消息发送到消息对象中
            Message message = new Message("02-send-way", "你好呀,异步请求,rocketmq".getBytes());
            //5 使用生产者发送信息，
            defaultMQProducer.send(message, new SendCallback() {
                public void onSuccess(SendResult sendResult) {
                    System.out.println("发送成功");
                    //进行减一操作
                    countDownLatch.countDown();
                }

                public void onException(Throwable throwable) {
                    System.out.println("发送失败");
                    //进行减一操作
                    countDownLatch.countDown();
                }
            });
        }
        //当countDownLatch结果减到0时,才放行
        countDownLatch.await();

        //异步发送时,要求生产者时开启的,在线的可以发送成功
        //Thread.sleep(10000);
        //6 关闭资源
        defaultMQProducer.shutdown();
    }
}
